<template>
  <div class="card" style="width: 100%; height: 100%">
    <div class="card table-main">
      <div class="table-header" v-if="isAdmin">
        <div class="header-button-lf">
          <el-button type="primary" :icon="Plus" @click="addUser">注册用户</el-button>
        </div>
      </div>
      <el-table :data="tableData" style="width: 100%; margin-bottom: 20px" row-key="id" border>
        <el-table-column type="index" label="序号" width="60" align="center"></el-table-column>
        <el-table-column prop="user" label="用户名" align="center" />
        <el-table-column :width="isAdmin ? 200 : 120" align="center" label="操作">
          <template #default="scope">
            <el-button type="primary" size="small" :icon="Brush" @click="handleReset(scope.row.user)" v-if="isAdmin">
              重置密码
            </el-button>
            <el-button type="danger" size="small" :icon="Delete" @click="handleDelete(scope.row.user)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-dialog
      v-model="dialogVisible"
      title="注册用户"
      width="500"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :before-close="handleClose"
    >
      <el-form :model="userForm" :rules="userRules" ref="userFormRef" label-width="100">
        <el-form-item label="用户名称" prop="username">
          <el-input v-model="userForm.username" placeholder="请输入用户名称"></el-input>
        </el-form-item>
        <el-form-item label="用户密码" prop="password">
          <el-input v-model="userForm.password" placeholder="请输入用户密码"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="handleConfirm">确认</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="userManagement">
import { ref } from "vue";
import { Delete, Plus, Brush } from "@element-plus/icons-vue";
import { deleteUserApi, getUserListApi, registerUserApi, resetPasswordApi } from "@/api/modules/business";
import { ElMessage, ElMessageBox } from "element-plus";
import { useUserStore } from "@/stores/modules/user";

const userStore = useUserStore();
const isAdmin = userStore.isAdmin;
const tableData = ref<{ user: string }[]>([]);
const dialogVisible = ref(false);
const userFormRef = ref<any>();
const userForm = ref({ username: "", password: "" });
const userRules = {
  username: { required: true, message: "请输入用户名称", trigger: "blur" },
  password: { required: true, message: "请输入用户密码", trigger: "blur" }
};

function addUser() {
  dialogVisible.value = true;
}

function handleClose() {
  dialogVisible.value = false;
  userForm.value = { username: "", password: "" };
  userFormRef.value.resetFields();
}

function handleConfirm() {
  userFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      const data = await registerUserApi({ ...userForm.value, permissions: ["normal users"] });
      ElMessage.success(data.message);
      handleClose();
      await getData();
    }
  });
}

function handleReset(user: string) {
  ElMessageBox.prompt("请输入重置的密码", `重置 ${user} 用户密码`, {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    inputPattern: /^[\s\S]*.*[^\s][\s\S]*$/,
    inputErrorMessage: "重置后的密码不能为空"
  }).then(async ({ value }) => {
    const params = { username: user, newPassword: value };
    const data = await resetPasswordApi(params);
    if (data.result) return ElMessage.success(data.message);
    ElMessage.error(data.message);
  });
}

function handleDelete(user: string) {
  console.log(user);
  ElMessageBox.confirm(`确认删除 ${user} 这条用户数据？`, "删除", {
    confirmButtonText: "确认",
    type: "warning",
    closeOnClickModal: false,
    closeOnPressEscape: false
  }).then(async () => {
    const data = await deleteUserApi(user);
    if (data.result) {
      ElMessage.success(data.message);
      await getData();
    } else {
      ElMessage.error(data.message);
    }
  });
}

async function getData() {
  const data = await getUserListApi();
  tableData.value = data.userList.map(item => {
    return { user: item };
  });
}

getData();
</script>

<style scoped lang="scss"></style>
